package com.zeus.activiti.web.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.zeus.activiti.web.activitiutil.ActivitiService;
import com.zeus.activiti.web.entity.Vacation;
import com.zeus.activiti.web.service.VacationService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/4.
 * this action will be to handle vacation process
 */
public class VacationAction extends ActionSupport implements SessionAware,RequestAware,ModelDriven<Vacation>
{
    private ActivitiService activitiService;
    private VacationService vacationService;
    private Map<String,Object> session,request;
    private Vacation vacation = null;

    public void setActivitiService(ActivitiService activitiService) {
        this.activitiService = activitiService;
    }

    public VacationService getVacationService() {
        return vacationService;
    }

    public void setVacationService(VacationService vacationService) {
        this.vacationService = vacationService;
    }

    @Override
    public void setRequest(Map<String, Object> request) {
        this.request = request;
    }

    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    @Override
    public Vacation getModel() {
        if(vacation ==null)
            vacation = new Vacation();
        return vacation;
    }

    public String start(){
        Map<String,Object> variables = new HashMap<String, Object>();
        System.out.println("test");

        ProcessInstance processInstance = activitiService.startProcessByKey("请假流程", null);
        vacation.setProcessId(processInstance.getId());
        Serializable vacationId = vacationService.save(vacation);
        variables.put("vacationId",vacationId);
        List<Task> tasks = activitiService.getPersonalTasks(vacation.getName(),processInstance.getId());
        if(tasks!=null && tasks.size()==1){
            Task task = tasks.get(0);
            activitiService.completeTask(task.getId(),variables);
        }
        request.put("vacation",vacation);
        return "start";
    }
}
